<template>
  <div class="app-container">
    <!-- 头部操作区域 -->
    <div class="header-section">
      <el-page-header @back="goBack" :content="`${formName} - 字段配置管理`" />
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" style="margin-left: 20px;">
        添加字段
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="listLoading" :data="fieldList" stripe style="width:100%; margin-top: 20px;">
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column prop="fieldName" label="字段名称" width="150" />
      <el-table-column prop="fieldCode" label="字段编码" width="150" />
      <el-table-column prop="fieldLabel" label="字段标签" width="150" />
      <el-table-column prop="fieldType" label="字段类型" width="120" />
      <el-table-column label="必填" width="80">
        <template slot-scope="scope">
          <el-tag :type="Number(scope.row.isRequired) === 1 ? 'danger' : 'info'" size="mini">
            {{ Number(scope.row.isRequired) === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="只读" width="80">
        <template slot-scope="scope">
          <el-tag :type="Number(scope.row.isReadonly) === 1 ? 'warning' : 'info'" size="mini">
            {{ Number(scope.row.isReadonly) === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="系统字段" width="100">
        <template slot-scope="scope">
          <el-tag :type="Number(scope.row.isSystem) === 1 ? 'success' : 'info'" size="mini">
            {{ Number(scope.row.isSystem) === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可排序" width="90">
        <template slot-scope="scope">
          <el-tag :type="Number(scope.row.isSort) === 1 ? 'success' : 'info'" size="mini">
            {{ Number(scope.row.isSort) === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" />
      <el-table-column label="操作" width="380" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleManageValidation(scope.row)">校验规则</el-button>
          <el-button type="primary" size="mini" @click="handleManageColor(scope.row)">颜色规则</el-button>
          <el-button type="success" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑字段弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :close-on-click-modal="false" width="50%">
      <el-form ref="fieldForm" :model="fieldForm" :rules="fieldRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段编码" prop="fieldCode">
              <el-input v-model="fieldForm.fieldCode" placeholder="请输入字段编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段标签" prop="fieldLabel">
              <el-input v-model="fieldForm.fieldLabel" placeholder="请输入字段标签" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型">
                <el-option label="文本输入" value="text" />
                <el-option label="数字输入" value="number" />
                <el-option label="日期选择" value="date" />
                <el-option label="下拉选择" value="select" />
                <el-option label="单选框" value="radio" />
                <el-option label="复选框" value="checkbox" />
                <el-option label="多行文本" value="textarea" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="占位提示" prop="placeholder">
              <el-input v-model="fieldForm.placeholder" placeholder="请输入占位提示" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认值" prop="defaultValue">
              <el-input v-model="fieldForm.defaultValue" placeholder="请输入默认值" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选项数据源" prop="optionsDataSource">
              <el-input v-model="fieldForm.optionsDataSource" placeholder="字典编码或API地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分组名称" prop="groupName">
              <el-input v-model="fieldForm.groupName" placeholder="请输入分组名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据库列类型" prop="dbColumnType">
              <el-select v-model="fieldForm.dbColumnType" placeholder="请选择数据库列类型">
                <el-option-group label="字符串类型">
                  <el-option label="VARCHAR(50) - 短文本" value="VARCHAR(50)" />
                  <el-option label="VARCHAR(100) - 中等文本" value="VARCHAR(100)" />
                  <el-option label="VARCHAR(255) - 标准文本（推荐）" value="VARCHAR(255)" />
                  <el-option label="VARCHAR(500) - 长文本" value="VARCHAR(500)" />
                  <el-option label="TEXT - 大文本" value="TEXT" />
                  <el-option label="LONGTEXT - 超大文本" value="LONGTEXT)" />
                </el-option-group>
                <el-option-group label="数字类型">
                  <el-option label="TINYINT - 极小整数(-128~127)" value="TINYINT" />
                  <el-option label="SMALLINT - 小整数(-32768~32767)" value="SMALLINT" />
                  <el-option label="INT - 整数（推荐）" value="INT" />
                  <el-option label="BIGINT - 大整数" value="BIGINT" />
                  <el-option label="DECIMAL(10,2) - 小数（推荐）" value="DECIMAL(10,2)" />
                  <el-option label="DECIMAL(15,4) - 高精度小数" value="DECIMAL(15,4)" />
                  <el-option label="FLOAT - 浮点数" value="FLOAT" />
                  <el-option label="DOUBLE - 双精度浮点数" value="DOUBLE" />
                </el-option-group>
                <el-option-group label="日期时间类型">
                  <el-option label="DATE - 日期" value="DATE" />
                  <el-option label="DATETIME - 日期时间（推荐）" value="DATETIME" />
                  <el-option label="TIMESTAMP - 时间戳" value="TIMESTAMP" />
                  <el-option label="TIME - 时间" value="TIME" />
                </el-option-group>
                <el-option-group label="其他类型">
                  <el-option label="BOOLEAN - 布尔值" value="BOOLEAN" />
                  <el-option label="JSON - JSON数据" value="JSON" />
                  <el-option label="BLOB - 二进制数据" value="BLOB" />
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                列类型说明
                <el-tooltip placement="top">
                  <div slot="content">
                    根据字段类型选择合适的数据库列类型：<br/>
                    • 文本输入 → VARCHAR(255)<br/>
                    • 多行文本 → TEXT<br/>
                    • 数字输入 → INT 或 DECIMAL(10,2)<br/>
                    • 日期选择 → DATE 或 DATETIME<br/>
                    • 下拉/单选 → VARCHAR(100)
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-input :value="getColumnTypeDescription(fieldForm.dbColumnType)" readonly placeholder="选择列类型后显示说明" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否必填">
              <el-switch v-model="fieldForm.isRequired" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否只读">
              <el-switch v-model="fieldForm.isReadonly" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否隐藏">
              <el-switch v-model="fieldForm.isHidden" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否系统字段">
              <el-switch v-model="fieldForm.isSystem" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可排序">
              <el-switch v-model="fieldForm.isSort" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="表格显示">
              <el-switch v-model="fieldForm.isShowInTable" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="表格列宽度">
              <el-input-number v-model="fieldForm.tableColumnWidth" :min="50" :max="500" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序号">
              <el-input-number v-model="fieldForm.sortOrder" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 校验规则管理弹窗 -->
    <el-dialog title="校验规则管理" :visible.sync="validationDialogVisible" :close-on-click-modal="false" width="60%">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddValidation" style="margin-bottom: 10px;">
        添加规则
      </el-button>
      <el-table :data="validationRules" stripe>
        <el-table-column prop="ruleType" label="规则类型" width="120" />
        <el-table-column prop="ruleValue" label="规则值" width="150" />
        <el-table-column prop="errorMessage" label="错误提示" min-width="200" />
        <el-table-column prop="triggerEvent" label="触发事件" width="100" />
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDeleteValidation(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 颜色规则管理弹窗 -->
    <el-dialog title="颜色规则管理" :visible.sync="colorDialogVisible" :close-on-click-modal="false" width="70%">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddColor" style="margin-bottom: 10px;">
        添加规则
      </el-button>
      <el-table :data="colorRules" stripe>
        <el-table-column prop="ruleName" label="规则名称" width="120" />
        <el-table-column prop="conditionType" label="条件类型" width="120" />
        <el-table-column prop="conditionValue" label="条件值" width="120" />
        <el-table-column label="文字颜色" width="100">
          <template slot-scope="scope">
            <div :style="{ color: scope.row.textColor }">{{ scope.row.textColor }}</div>
          </template>
        </el-table-column>
        <el-table-column label="背景颜色" width="100">
          <template slot-scope="scope">
            <div :style="{ backgroundColor: scope.row.backgroundColor, padding: '4px' }">{{ scope.row.backgroundColor }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDeleteColor(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFieldListByFormId,
  createFieldConfig,
  updateFieldConfig,
  deleteFieldConfig,
  getValidationRules,
  deleteValidationRule,
  getColorRules,
  deleteColorRule
} from '@/api/field'

export default {
  name: 'FieldConfigManage',
  data() {
    return {
      formId: '',
      formName: '',
      formCode: '',
      listLoading: false,
      fieldList: [],
      dialogVisible: false,
      dialogTitle: '添加字段',
      isEdit: false,
      fieldForm: {
        formId: '',
        fieldCode: '',
        fieldName: '',
        fieldType: '',
        fieldLabel: '',
        placeholder: '',
        defaultValue: '',
        isRequired: 0,
        isReadonly: 0,
        isHidden: 0,
        isSystem: 0,
        isSort: 0,
        isShowInTable: 1,
        tableColumnWidth: 150,
        sortOrder: 0,
        optionsData: '',
        optionsDataSource: '',
        groupName: '',
        dbColumnType: 'VARCHAR(255)' // 默认数据库列类型
      },
      fieldRules: {
        fieldName: [
          { required: true, message: '请输入字段名称', trigger: 'blur' }
        ],
        fieldCode: [
          { required: true, message: '请输入字段编码', trigger: 'blur' }
        ],
        fieldLabel: [
          { required: true, message: '请输入字段标签', trigger: 'blur' }
        ],
        fieldType: [
          { required: true, message: '请选择字段类型', trigger: 'change' }
        ]
      },
      // 校验规则相关
      validationDialogVisible: false,
      currentField: null,
      validationRules: [],
      // 颜色规则相关
      colorDialogVisible: false,
      colorRules: []
    }
  },
  mounted() {
    this.formId = this.$route.query.formId
    this.formName = this.$route.query.formName
    this.formCode = this.$route.query.formCode
    if (!this.formId) {
      this.$message.error('缺少表单ID参数')
      this.goBack()
      return
    }
    this.getFieldList()
  },
  methods: {
    getInitFieldForm() {
      return {
        formId: this.formId,
        fieldCode: '',
        fieldName: '',
        fieldType: '',
        fieldLabel: '',
        placeholder: '',
        defaultValue: '',
        isRequired: 0,
        isReadonly: 0,
        isHidden: 0,
        isSystem: 0,
        isSort: 0,
        isShowInTable: 1,
        tableColumnWidth: 150,
        sortOrder: 0,
        optionsData: '',
        optionsDataSource: '',
        groupName: '',
        dbColumnType: 'VARCHAR(255)' // 默认数据库列类型
      }
    },
    // 返回
    goBack() {
      this.$router.back()
    },
    // 获取字段列表
    getFieldList() {
      this.listLoading = true
      getFieldListByFormId(this.formId).then(res => {
        if (res.code === 200) {
          this.fieldList = res.result
          // 调试：查看后端返回的实际数据
          console.log('=== 字段列表数据 ===')
          console.log('完整数据:', res.result)
          if (res.result && res.result.length > 0) {
            console.log('第一条数据的isSystem值:', res.result[0].isSystem)
            console.log('isSystem的类型:', typeof res.result[0].isSystem)
          }
        }
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 添加字段
    handleAdd() {
      this.dialogTitle = '添加字段'
      this.isEdit = false
      this.fieldForm = this.getInitFieldForm()
      this.fieldForm.formId = this.formId
      this.dialogVisible = true
    },
    // 编辑字段
    handleEdit(row) {
      this.dialogTitle = '编辑字段'
      this.isEdit = true
      this.fieldForm = { ...row }
      this.dialogVisible = true
    },
    // 提交
    handleSubmit() {
      this.$refs.fieldForm.validate(valid => {
        if (valid) {
          console.log('提交的字段数据:', this.fieldForm)
          if (this.isEdit) {
            updateFieldConfig(this.fieldForm.id, this.fieldForm).then(res => {
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.dialogVisible = false
                this.getFieldList()
              }
            })
          } else {
            createFieldConfig(this.fieldForm).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功')
                this.dialogVisible = false
                this.getFieldList()
              }
            })
          }
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该字段吗？删除后对应的规则也会被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFieldConfig(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getFieldList()
          }
        })
      })
    },
    // 管理校验规则
    handleManageValidation(row) {
      this.currentField = row
      this.validationDialogVisible = true
      this.loadValidationRules(row.id)
    },
    // 加载校验规则
    loadValidationRules(fieldId) {
      getValidationRules(fieldId).then(res => {
        if (res.code === 200) {
          this.validationRules = res.result
        }
      })
    },
    // 添加校验规则（简化版，实际应该有独立的表单）
    handleAddValidation() {
      this.$message.info('请在此处添加校验规则表单逻辑')
    },
    // 删除校验规则
    handleDeleteValidation(row) {
      this.$confirm('确定要删除该校验规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteValidationRule(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.loadValidationRules(this.currentField.id)
          }
        })
      })
    },
    // 管理颜色规则
    handleManageColor(row) {
      this.currentField = row
      this.colorDialogVisible = true
      this.loadColorRules(row.id)
    },
    // 加载颜色规则
    loadColorRules(fieldId) {
      getColorRules(fieldId).then(res => {
        if (res.code === 200) {
          this.colorRules = res.result
        }
      })
    },
    // 添加颜色规则（简化版，实际应该有独立的表单）
    handleAddColor() {
      this.$message.info('请在此处添加颜色规则表单逻辑')
    },
    // 删除颜色规则
    handleDeleteColor(row) {
      this.$confirm('确定要删除该颜色规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteColorRule(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.loadColorRules(this.currentField.id)
          }
        })
      })
    },
    // 获取数据库列类型说明
    getColumnTypeDescription(columnType) {
      const descriptions = {
        'VARCHAR(50)': '适合存储短文本，如用户名、简称（最大50字符）',
        'VARCHAR(100)': '适合存储中等长度文本，如标题、名称（最大100字符）',
        'VARCHAR(255)': '标准文本存储，适合大多数场景（最大255字符）',
        'VARCHAR(500)': '适合存储较长文本，如地址、描述（最大500字符）',
        'TEXT': '大文本存储，适合文章内容、备注等（最大65535字符）',
        'LONGTEXT': '超大文本存储，适合富文本、长文档（最大4GB）',
        'TINYINT': '极小整数，范围-128到127，适合状态标识',
        'SMALLINT': '小整数，范围-32768到32767，适合数量统计',
        'INT': '标准整数，范围约-21亿到21亿，适合大多数整数场景',
        'BIGINT': '大整数，范围约-922亿亿到922亿亿，适合ID、计数器',
        'DECIMAL(10,2)': '精确小数，10位总长度，2位小数，适合金额',
        'DECIMAL(15,4)': '高精度小数，15位总长度，4位小数，适合精密计算',
        'FLOAT': '单精度浮点数，适合科学计算（可能有精度损失）',
        'DOUBLE': '双精度浮点数，适合高精度科学计算',
        'DATE': '仅存储日期（YYYY-MM-DD），不包含时间',
        'DATETIME': '存储日期和时间（YYYY-MM-DD HH:MM:SS）',
        'TIMESTAMP': '时间戳，自动记录创建/更新时间',
        'TIME': '仅存储时间（HH:MM:SS）',
        'BOOLEAN': '布尔值，存储true/false或0/1',
        'JSON': 'JSON格式数据，适合存储复杂结构',
        'BLOB': '二进制数据，适合存储文件、图片'
      }
      return descriptions[columnType] || '请选择数据库列类型'
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>
